# -*- encoding:utf-8 -*-
# @time:2022-11-18 14:51
# @Author : serein
# @Email: serein@qq.com
# @File:serializers.py
# @Software: PyCharm
from django.contrib.auth.models import User
from rest_framework import serializers
from users.models import UserDetail


class UserDetailSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserDetail
        exclude = ['is_delete','create_time','update_time']
        extra_kwargs = {
            'avatar':{'read_only':True},
            'user': {'required': False, 'write_only': True}
        }
#     Django表单字段如：forms.CharField, forms.EmailField等，会默认传入参数required=True，也就是默认表单字段不能为空
#serializers.ModelSerializer等同于ModelSerializer
class UserSerializer(serializers.ModelSerializer):
    #这个字段不能加逗号,这个字段要是这个类的缩写,除了serializer之外的所有单词缩写
    userdetail = UserDetailSerializer(required=False,read_only=True)
    class Meta:
        model = User
        exclude = ['password','last_name','user_permissions']
        extra_kwargs = {
            'id':{'read_only':True},
            'last_login':{'read_only':True},
            'is_superuser':{'read_only':True},
            'is_staff':{'read_only':True},
            'is_active':{'read_only':True},
            'groups':{'read_only':True},
            'data_joined':{'read_only':True},
        }
# 查看用户账户信息序列化器
class CheickUserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['id','username','email']
        extra_kwargs = {
            'id':{'read_only':True},
            'username':{'read_only':True},
            'email':{'read_only':True}
        }

class UpdataSerializer(serializers.Serializer):
    # 用户名
    # 旧密码
    # 新密码
    # 确认新密码
    # 邮箱
    first_name = serializers.CharField(max_length=40,label='用户名')
    password = serializers.CharField(max_length=60,label='旧密码')
    new_password = serializers.CharField(max_length=60,label='新密码')
    re_new_password = serializers.CharField(max_length=60,label='新密码')
    new_email =  serializers.EmailField(max_length=40,label='邮箱')
    def validate(self, attrs):
        if attrs['new_password'] != attrs['re_new_password']:
            raise serializers.ValidationError('两次密码输入不一致')
        if attrs['first_name'] == '':
            raise serializers.ValidationError('用户名不能为空')
        if attrs['new_email'] == '':
            raise serializers.ValidationError('邮箱不能为空')
        return attrs


class UpdateUserAvaterSerializer(serializers.Serializer):
    avatar = serializers.ImageField(max_length=200,label='头像')
